package NG::Sys::TT;
use strict;
use warnings;
use utf8;

use JSON::XS;
my $json;

sub new {
	my ($class,$app) = @_;

	require Template;
	
	my $tt = Template->new({
		INCLUDE_PATH => $app->{cfg}{path}{template},
		ANYCASE => 1,
		RELATIVE => 1,
		START_TAG => quotemeta('[%'),
		END_TAG   => quotemeta('%]'),
		PRE_PROCESS => [],
		POST_PROCESS => [],
		ENCODING => 'utf8',
		STAT_TTL => 3600,
	});
	my $self = bless {tt=>$tt,app=>$app},$class;
	$self->init;
	return $self;
}
sub init {
	my ($self) = @_;
	my $tc = $self->{tt}->context;

	#$tc->define_filter(bigint => \&TT::Addon::bigint,1);
	#$tc->define_vmethod(hash  => Dumper =>
	#				sub {
	#					my $hash = shift;
	#					require Data::Dumper;
	#					return Data::Dumper::Dumper($hash);
	#				});
	$json = JSON::XS->new->utf8(0);
	
	$tc->define_vmethod(hash  => json =>
					sub {
						my $hash = shift;
						my $pretty = shift;
						return $json->pretty(!!$pretty)->encode($hash);
					});
	$tc->define_vmethod(list  => json =>
					sub {
						my $list = shift;
						my $pretty = shift;
						return $json->pretty(!!$pretty)->encode($list);
					});

}
sub read {
	my $self = shift;
	my $fn = shift;
	$fn =~ s/\.html$//;
	return NG::Sys::TT::TT->new($self,$fn.".html");
}

package NG::Sys::TT::TT;
use strict;
use Time::HiRes qw(gettimeofday tv_interval);

sub new {
	my ($class,$tt,$fn) = @_;
	return bless {
		app => $tt->{app},
		tt => $tt->{tt},
		fn => $fn,
		},$class;
}

sub process {
	my $self = shift;
	my $data = shift;
	my $r0 = [gettimeofday];

	my $out = "";
	require Template;
	my $te = $Template::ERROR;
	unless($self->{tt}->process($self->{fn},$data,\$out)){
		my $msg = "TEMPLATE(".$self->{fn}."): '".$Template::ERROR."' '".$self->{tt}->error."'";
		die $msg;
	}

	my $t = tv_interval($r0);

	my $c = $self->{app}->get_context("template_time");
	($c->{time} ||= 0) += $t;

	return $out;
}

1;
